<template>
    <div class="role-list">
        <!-- Search and Add Button -->
        <div class="operation-bar">
            <el-input v-model="searchKeyword" placeholder="请输入角色名称/代码" style="width: 200px" @keyup.enter="handleSearch">
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>

        <!-- Table -->
        <el-table :data="roleList" border style="width: 100%; margin-top: 20px">
            <el-table-column prop="id" label="角色id" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="code" label="角色代码" />
            <el-table-column prop="description" label="角色描述" show-overflow-tooltip />
            <el-table-column prop="is_active" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.is_active ? 'success' : 'info'">
                        {{ row.is_active ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
                <template #default="{ row }">
                    {{ formatDateTime(row.created_at) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="success" size="small" @click="handleAssignMenus(row)">分配菜单</el-button>
                    <el-button :type="row.is_active ? 'warning' : 'success'" size="small"
                        @click="handleToggleStatus(row)">
                        {{ row.is_active ? '禁用' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- Role Form Dialog -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
            <el-form :model="roleForm" :rules="rules" ref="roleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="roleForm.name" />
                </el-form-item>
                <el-form-item label="角色代码" prop="code">
                    <el-input v-model="roleForm.code" :disabled="dialogTitle === '编辑角色'" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input type="textarea" v-model="roleForm.description" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="roleForm.is_active" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>

        <!-- Menu Assignment Dialog -->
        <el-dialog title="分配菜单" v-model="menuDialogVisible" width="600px" @closed="handleMenuDialogClosed">
            <div class="menu-tree-operations">
                <el-button size="small" type="primary" plain @click="handleToggleExpand">
                    <el-icon>
                        <component :is="isExpanded ? 'Fold' : 'Expand'" />
                    </el-icon>
                    {{ isExpanded ? '折叠全部' : '展开全部' }}
                </el-button>
            </div>
            <el-tree ref="menuTreeRef" :check-on-click-node="true" :check-strictly="true" :data="menuTree" show-checkbox
                node-key="id" :props="{
                    label: 'title',
                    children: 'children'
                }" :default-checked-keys="selectedMenuIds" />
            <template #footer>
                <el-button @click="menuDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleMenuSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Expand, Fold } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import http from '@/utils/http'

// 数据定义
const searchKeyword = ref('')
const roleList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const roleFormRef = ref(null)
const menuDialogVisible = ref(false)
const menuTreeRef = ref(null)
const menuTree = ref([])
const selectedMenuIds = ref([])
const currentRoleId = ref(null)

const roleForm = reactive({
    name: '',
    code: '',
    description: '',
    is_active: true
})

const rules = {
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入角色代码', trigger: 'blur' }],
    description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
}

// 获取角色列表
const getRoleList = async () => {
  try {
      // 模拟API请求
      const data = await http.get('/roles')
      roleList.value = data
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 获取菜单树
const getMenuTree = async () => {
  try {
      // 模拟API请求
      const data = await http.get('/menus/tree?all=1')
      menuTree.value = data
  } catch (error) {
    ElMessage.error('获取菜单树失败')
  }
}

// 处理搜索
const handleSearch = () => {
  const keyword = searchKeyword.value.toLowerCase()
  roleList.value = mockRoleList.filter(role => 
    role.name.toLowerCase().includes(keyword) || 
    role.code.toLowerCase().includes(keyword)
  )
}

// 处理添加角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  roleForm.name = ''
  roleForm.code = ''
  roleForm.description = ''
  roleForm.is_active = true
  dialogVisible.value = true
}

// 处理编辑角色
const handleEdit = (row) => {
    currentRoleId.value = row.id
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, row)
  dialogVisible.value = true
}

// 处理表单提交
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
      if (dialogTitle.value === '新增角色') {
          // 剔除roleForm.id外，其余数据提交
          await http.post('/roles', roleForm)
        ElMessage.success('添加成功')
      } else {
          const { id, ...data } = roleForm
          await http.put(`/roles/${currentRoleId.value}`, data)
        ElMessage.success('添加成功')
      ElMessage.success('编辑成功')
      }
    
    dialogVisible.value = false
    getRoleList()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理状态切换
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}该角色吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟状态更新
    const role = mockRoleList.find(r => role.id === row.id)
    if (role) {
      role.is_active = !role.is_active
      getRoleList()
      ElMessage.success(`${role.is_active ? '启用' : '禁用'}成功`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 处理菜单分配
const handleAssignMenus = async (row) => {
  currentRoleId.value = row.id
    // 模拟获取角色菜单
  await http.get(`/roles/${row.id}/menus`).then(data => {
      selectedMenuIds.value = data.map(menu => menu.id)
      menuDialogVisible.value = true
  })
}

// 处理菜单分配提交
const handleMenuSubmit = async () => {
  try {
      const checkedKeys = menuTreeRef.value.getCheckedKeys()
    // :chekck-strictly 模式下，半选状态的节点需要手动获取
      const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()

      // 合并全选和半选的节点ID
      const allSelectedKeys = [...checkedKeys, ...halfCheckedKeys]
    
    // 模拟提交
      console.log('分配的菜单IDs:', checkedKeys)
      await new http.put(`/roles/${currentRoleId.value}/menus`, { menu_ids: allSelectedKeys })
    
    ElMessage.success('菜单分配成功')
    menuDialogVisible.value = false
  } catch (error) {
    ElMessage.error('菜单分配失败')
  }
}

// 处理展开状态控制
const isExpanded = ref(false)

// 合并展开和折叠功能
const handleToggleExpand = () => {
  const tree = menuTreeRef.value
  if (tree) {
    isExpanded.value = !isExpanded.value
    tree.store.nodesMap && Object.values(tree.store.nodesMap).forEach(node => {
      node.expanded = isExpanded.value
    })
  }
}

// 处理对话框关闭
const handleMenuDialogClosed = () => {
  selectedMenuIds.value = []
  if (menuTreeRef.value) {
    menuTreeRef.value.setCheckedKeys([])
  }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
    getRoleList()
    getMenuTree()
})
</script>

<style scoped>
.role-list {
    padding: 20px;
}
.operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.el-dialog__body {
    padding-top: 20px;
}

.menu-tree-operations {
  margin-bottom: 16px;
  padding: 8px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  text-align: right; /* 右对齐按钮 */
}

.menu-tree-operations .el-button-group {
  display: flex;
  gap: 8px;
}

.menu-tree-operations .el-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

/* 优化树形控件的样式 */
:deep(.el-tree) {
  background-color: transparent;
  padding: 8px;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.el-tree-node__content:hover) {
  background-color: var(--el-fill-color-light);
}
</style>